package next.apps.controller;

import next.apps.bean.GoodsDetail;
import next.apps.bean.OrderData;
import next.apps.bean.OrderInfo;
import next.apps.bean.StockInfo;
import next.apps.service.OrderService;
import next.apps.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private StockService stockService;

    @PostMapping("/merge")
    public Map<String,Integer> numberMerge(@RequestBody GoodsDetail detail){
        return stockService.mergeNumber(detail);
    }

    @PostMapping("/save")
    @Transactional
    public void saveOrder(@RequestBody OrderData order,String orderId){
        List<OrderInfo> orderInfoList = order.getOrder();
        List<String> goodsIdList = new ArrayList<>();
        Map<String,Integer> map = new HashMap<>();
        for (OrderInfo orderInfo : orderInfoList) {
            if(!goodsIdList.contains(orderInfo.getGoodsId())){
                goodsIdList.add(orderInfo.getGoodsId());
            }

            if(map.containsKey(orderInfo.getGoodsId())){
                map.put(orderInfo.getGoodsId(),map.get(orderInfo.getGoodsId()) + orderInfo.getNumber());
            }else{
                map.put(orderInfo.getGoodsId(),orderInfo.getNumber());
            }
        }
        List<StockInfo> stockInfoList = stockService.selectByGoodsId(goodsIdList);
        stockInfoList.forEach(item ->{
            if(map.get(item.getGoodsId()) > item.getNumber()){
                throw new RuntimeException("库存不足.......");
            }
            item.setNumber(item.getNumber() - map.get(item.getGoodsId()));
        });
        orderService.save(orderInfoList,orderId);
        stockService.updateByList(stockInfoList);
    }
}
